import React, { PureComponent } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Link } from 'dva/router';
import { Row, Col, Card, List, Avatar,Button,Skeleton,Divider,Statistic } from 'antd';

import { Radar } from 'components/Charts';
import EditableLinkGroup from 'components/EditableLinkGroup';
import PageHeaderLayout from './../layouts/PageHeaderLayout';
import styles from './Workbanch.less';
import numeral from 'numeral';

const links = [
  {
    title: '提测管理',
    href: '/testcenter/testrecord',
  },
  {
    title: '项目概览',
    href:'/quality/overview',
  },
  {
    title:'项目管理',
    href:'/testcenter/projectmanage',
  },
  {
    title:'用户管理',
    href:'/system/usermanage',
  },


];

const members = [
  {
    id: 'members-1',
    title: '科学搬砖组',
    logo: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png',
    link: '',
  },
  {
    id: 'members-2',
    title: '程序员日常',
    logo: 'https://gw.alipayobjects.com/zos/rmsportal/cnrhVkzwxjPwAaCfPbdc.png',
    link: '',
  },
  {
    id: 'members-3',
    title: '设计天团',
    logo: 'https://gw.alipayobjects.com/zos/rmsportal/gaOngJwsRYRaVAuXXcmB.png',
    link: '',
  },
  {
    id: 'members-4',
    title: '中二少女团',
    logo: 'https://gw.alipayobjects.com/zos/rmsportal/ubnKSIfAJTxIgXOKlciN.png',
    link: '',
  },
  {
    id: 'members-5',
    title: '骗你学计算机',
    logo: 'https://gw.alipayobjects.com/zos/rmsportal/WhxKECPNujWoWEFNdnJE.png',
    link: '',
  },
];

// const avatars = [
//   '../dist/public/src/assets/laserbox.png',
//   '../dist/public/src/assets/mBlock.png', // mBlockPC
//   '../dist/public/src/assets/mBlock1.png', // mBlockAPP
//   '../dist/public/src/assets/MakeblockAPP.png', // MakeblockAPP
//   '../dist/public/src/assets/Neuron1.png', // Neuron
//   'https://gw.alipayobjects.com/zos/rmsportal/siCrBXXhmvTQGWPNLBow.png', // LaserBox
//   '../dist/public/src/assets/makex.png', // MakeX
//   '../dist/public/src/assets/Neuron.png',
//   '../dist/public/src/assets/Neuron2.png',
//   '../dist/public/src/assets/Neuron.png',
//   '../dist/public/src/assets/Neuron2.png',
//   '../dist/public/src/assets/Neuron.png',
//   '../dist/public/src/assets/Neuron2.png',
//   '../dist/public/src/assets/Neuron.png',
//   '../dist/public/src/assets/Neuron2.png',
//   '../dist/public/src/assets/Neuron.png',
//   '../dist/public/src/assets/Neuron2.png',
// ];
const titles = [
  'Unity3D',
  'LaserBox',
  'mBlock',
  'MakeX',
  'MBextend',
  'MBclassroom',
  'MBforum',
  'Education',
  'Neuron',
  'mBlockAPP',
  'MakeblockForiOS',
  'MakeblockForAndroid',
  'Corbit',
  'MBcourse',
  'BoxWeChat'
];

const avatars = [

  'https://s2.ax1x.com/2019/01/19/kCel7D.png', //Unity3D 11105
  'https://s2.ax1x.com/2019/01/19/kCe8tH.png', //LaserBox 10907
  'https://s2.ax1x.com/2019/01/19/kCeMnK.png', //mBlock  10208
  'https://s2.ax1x.com/2019/01/19/kCen6x.png', //MakeX  10700
  'https://s2.ax1x.com/2019/01/19/kCeuX6.png', //MBextend  11219 //需要修改后台
  'https://s2.ax1x.com/2019/01/19/kCe3Ae.png', //MBclassroom 11104
  'https://s2.ax1x.com/2019/01/19/kCeGhd.png', //MBforum 11107
  'https://s2.ax1x.com/2019/01/19/kCeQ0O.png', //Education 10209  /需要修改后台
  'https://s2.ax1x.com/2019/01/19/kCet1I.png', //Neuron 10300 
  'https://s2.ax1x.com/2019/03/04/kOzQTx.png', //mBlockAPP 11106
  'https://s2.ax1x.com/2019/01/19/kCeY9A.png', //MakeblockForiOS 10100
  'https://s2.ax1x.com/2019/01/19/kCeNct.png',  //MakeblockForAndroid 10204
  'https://s2.ax1x.com/2019/01/19/kCeUjP.png', // Corbit 11300
  'https://s2.ax1x.com/2019/01/19/kCeUjP.png', // MBcourse 11302
  'https://s2.ax1x.com/2019/01/22/kFYsEQ.png',//BoxWeChat 11400
];

const LocalNotice = [
  {
    id: '11105',
    title: titles[0],
    logo: avatars[0],
    description: '提供用户虚拟搭建公司硬件产品的平台',
    updatedAt: new Date(),
    member: '3D搭建',
    href: '/quality/singleProject/11105',
    memberLink: '',
  },
  {
    id: '10907',
    title: titles[1],
    logo: avatars[1],
    description: '让普通用户也能轻松使用的激光切割机，像画笔一样发挥创意',
    updatedAt: new Date(),
    member: '激光切割机|激光宝盒',
    href: '/quality/singleProject/10907',
    memberLink: '',
  },
  {
    id: '10208',
    title: titles[2],
    logo: avatars[2],
    description: '最好的图形化编程创作、学习、教育工具，帮助人们在物理和数字世界中通过编程来创造',
    updatedAt: new Date(),
    member: 'mBlock慧编程PC端',
    href: '/quality/singleProject/10208',
    memberLink: '',
  },
  {
    id: '10700',
    title: titles[3],
    logo: avatars[3],
    description: '一款简单、省心的赛事工具，陪伴STEAM教育用户成长',
    updatedAt: new Date(),
    member: '平台赛事',
    href: '/quality/singleProject/10700',
    memberLink: '',
  },
  {
    id: '11219',
    title: titles[4],
    logo: avatars[4],
    description: '慧编程扩展设计器，提供用户扩展设计能力的平台',
    updatedAt: new Date(),
    member: 'mBlock慧编程扩展设计器',
    href: '/quality/singleProject/11219',
    memberLink: '',
  },
  {
    id: '11104',
    title: titles[5],
    logo: avatars[5],
    description: '慧编程课堂管理工具，提供教师与学生传授管理知识的平台',
    updatedAt: new Date(),
    member: 'mBlock慧编程课堂管理工具',
    href: '/quality/singleProject/11104',
    memberLink: '',
  },
  {
    id: '11107',
    title: titles[6],
    logo: avatars[6],
    description: '慧编程社区，提供用户作品展示与交流的平台',
    updatedAt: new Date(),
    member: 'mBlock慧编程社区',
    href: '/quality/singleProject/11107',
    memberLink: '',
  },
  {
    id: '10209',
    title: titles[7],
    logo: avatars[7],
    description: '为使用Makeblock产品的教育者提供教学支持， 促进教育者之间的分享与交流',
    updatedAt: new Date(),
    member: '教育站',
    href: '/quality/singleProject/10209',
    memberLink: '',
  },
  {
    id: '10300',
    title: titles[8],
    logo: avatars[8],
    description: '"neuron,make everything, make anything."——最直观、最灵活的创造电子模块的方式',
    updatedAt: new Date(),
    member: '神经元移动端|包含Android&iOS',
    href: '/quality/singleProject/10300',
    memberLink: '',
  },
  {
    id: '11106',
    title: titles[9],
    logo: avatars[9],
    description: '最好的图形化编程创作、学习、教育工具，帮助人们在物理和数字世界中通过编程来创造',
    updatedAt: new Date(),
    member: '慧编程移动端|包含Android&iOS',
    href: '/quality/singleProject/11106',
    memberLink: '',
  },
  {
    id: '10100',
    title: titles[10],
    logo: avatars[10],
    description: '提供人和机器人交互，学习了解机器人，通过机器人享受丰富的STEAM世界的最好体验',
    updatedAt: new Date(),
    member: 'MakeblockAPP苹果端',
    href: '/quality/singleProject/10100',
    memberLink: '',
  },
  {
    id: '10204',
    title: titles[11],
    logo: avatars[11],
    description: '提供人和机器人交互，学习了解机器人，通过机器人享受丰富的STEAM世界的最好体验',
    updatedAt: new Date(),
    member: 'MakeblockAPP安卓端',
    href: '/quality/singleProject/10204',
    memberLink: '',
  },
  {
    id: '11300',
    title: titles[12],
    logo: avatars[12],
    description: 'discovery的版权，还在申请中。图片文案还不能开放',
    updatedAt: new Date(),
    member: 'Corbit',
    href: '/quality/singleProject/11300',
    memberLink: '',
  },
  {
    id: '11302',
    title: titles[13],
    logo: avatars[13],
    description: '课程内容管理平台',
    updatedAt: new Date(),
    member: 'MBcourse',
    href: '/quality/singleProject/11302',
    memberLink: '',
  },
  {
    id: '11400',
    title: titles[14],
    logo: avatars[14],
    description: '家庭盒子',
    updatedAt: new Date(),
    member: 'BoxWeChat',
    href: '/quality/singleProject/11400',
    memberLink: '',
  },
];


@connect(({ loading,user ,workactivities,jira,singpro}) => ({
  user,
  workactivities,
  wprojectLoading: loading.effects['workproject/dynamiclogsList'],
  wactivitiesLoading: loading.effects['workactivities/dynamiclogsList'],
  bugProjectTotal: jira.bug.bugProjectTotal,
  qualitysum: singpro.SinglequalitySum.qualitysum,
}))
export default class Workbanch extends PureComponent {


  componentDidMount() {
    const { dispatch } = this.props;
    // 临时写死替代mock请求，保留作为后面改写请求后台的形式。
    // dispatch({
    //   type: 'workproject/wfetchNotice',
    // });
    dispatch({
      type: 'workactivities/dynamiclogsList',
    });
    this.props.dispatch({
      type: 'jira/fetchJiraData',
    })
    this.props.dispatch({
      type: 'singpro/fetchqualitysum',
    })

  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'chart/clear',
    });
  }

  getSingproCardInfo = (bugTotalData, qualitysumData) => {
    const result = []
    const qualitysumRes = this.getQualityRanking(qualitysumData)
    for(let i = 0; i < LocalNotice.length; i += 1){
      const elem = {...LocalNotice[i]}
      elem.count = LocalNotice.length
      for(let j=0; j < bugTotalData.length; j += 1){
        if(LocalNotice[i].title === bugTotalData[j].x){
          elem.bugTotal = bugTotalData[j].y
          break
        }
      }
      for(let j=0; j < qualitysumRes.length; j++){
        if(LocalNotice[i].title === qualitysumRes[j].name){
          elem.quality = qualitysumRes[j].y
          elem.rank = j + 1
          break
        }
      }
      result.push(elem)
    }
    return result
  };

  getQualityRanking = (data) =>{
    const qualityCount = {};
    const qualityList = [];
    for(const i in data){
      if(qualityCount[data[i].name]){
        qualityCount[data[i].name] += data[i].value;
      }else{
        qualityCount[data[i].name] = data[i].value;
      }
    }
    Object.keys(qualityCount).forEach((key) => {
      qualityList.push({name:key,y:qualityCount[key]});
    });

    qualityList.sort(this.compare);

    return qualityList;
  };

  compare = function (obj1, obj2) {
    const val1 = obj1.y;
    const val2 = obj2.y;
    if (val1 < val2) {
      return 1;
    } else if (val1 > val2) {
      return -1;
    } else {
      return 0;
    }
  };


  renderListLogs(){
    let { workactivities }=this.props
    let {data} =workactivities
    //console.log('!!!data',data)
    return   data.map((item,index)=>{

      return (
        <List.Item key={index} >{/*pagination*/}
          <List.Item.Meta
            avatar={<Avatar style={{ backgroundColor: '#87d068' }} icon="user"  />}//src={item.user.avatar}
            title={
              <span>
                <span className={styles.event}>{item.log}</span>
              </span>
            }
            description={
              <span className={styles.datetime} >
                {moment(item.CreationTime).fromNow()}
              </span>
            }
          />
        </List.Item>
      )


    })
  }


  renderActivities() {
    //const { workactivities: { list } } = this.props;
    return wgetActivities.map(item => {
      const events = item.template.split(/@\{([^{}]*)\}/gi).map(key => {
        if (item[key]) {
          return (
            <a href={item[key].link} key={item[key].name}>
              {item[key].name}
            </a>
          );
        }
        return key;
      });
      return (
        <List.Item key={item.id}>
          <List.Item.Meta
            avatar={<Avatar style={{ backgroundColor: '#87d068' }} icon="user"  />}//src={item.user.avatar}
            title={
              <span>
                <a className={styles.username}>{item.user.name}</a>
                &nbsp;
                <span className={styles.event}>{events}</span>
              </span>
            }
            description={
              <span className={styles.datetime} title={item.updatedAt}>
                {moment(item.updatedAt).fromNow()}
              </span>
            }
          />
        </List.Item>
      );
    });
  }

  getDatetime(currentUser){


    let nowHours=new Date().getHours()

    if (nowHours < 6){
      return <span>凌晨好！{currentUser.realName},  天还没亮，夜猫子，早点休息吧！</span>
    }
    else if(nowHours < 9){
      return <span>早上好！{currentUser.realName},  注意查看项目进度，上班加油！</span>
    }
    else if(nowHours < 12){
      return <span>上午好！{currentUser.realName},  火力全开！</span>
    }
    else if (nowHours < 14){
      return <span>中午好！{currentUser.realName},  熄火午休，下午精力充沛！</span>
    }
    else if (nowHours < 18){
      return <span>下午好！{currentUser.realName},  持续加速，请保持！</span>
    }
    else if (nowHours < 22){
      return <span>晚上好！{currentUser.realName},  早点回家，注意安全！</span>
    }
    else{
      return <span>深夜好！{currentUser.realName},  很晚了！本钱不能丢！</span>
    }
  }
  getDynameicAction(action){
    let result = '';

      switch(action){
          case null:
            result = '';
            break;
          case "delete":
            result = "删除项目";
            break;
          case "v_delete":
            result = "删除版本";
            break;
          case "insert":
            result ="新增项目";
            break;
          case "v_insert":
            result ="新增版本";
            break;
          case "update":
            result ="修改项目";
            break;
          case "v_update":
            result ="修改版本";
          case "report_update":
            result ="已发布版本"
            break;
      }
      return result;
  }
  render() {
    const {
      workactivities,
      wprojectLoading,
      wactivitiesLoading,
      user,
      bugProjectTotal,
      qualitysum
    } = this.props;

    let {data} =workactivities

   // console.log('@@@@',workactivities ,'@@props',this.props,'logs',data)
    const {
      currentUser
    }=user

    const pageHeaderContent = (
      <div className={styles.pageHeaderContent}>
        <div className={styles.avatar}>
          <Avatar size="large" src="https://s2.ax1x.com/2019/01/22/kFYsEQ.png" />
        </div>
        <div className={styles.content}>
          <div className={styles.contentTitle}>{this.getDatetime(currentUser)}</div>
          <div>Makeblock－互联网业务部</div>
        </div>
      </div>
    );

    const extraContent = (
      <div className={styles.extraContent}>
        <div className={styles.statItem}>
          <p>质量系数</p>
          <p>19</p>
        </div>
        <div className={styles.statItem}>
          <p>质量排名</p>
          <p>
            8<span> / 24</span>
          </p>
        </div>
        <div className={styles.statItem}>
          <p>Bug总数</p>
          <p>2,223</p>
        </div>
      </div>
    );

    return (
      // <PageHeaderLayout content={pageHeaderContent} extraContent={extraContent}>
      <PageHeaderLayout content={pageHeaderContent} >
        <Row gutter={24}>
          <Col xl={16} lg={24} md={24} sm={24} xs={24}>
            <Card
              className={styles.projectList}
              style={{ marginBottom: 24 }}
              title="进行中的项目"
              bordered={false}
              extra={<Link to="/quality/overview">全部项目</Link>}
              loading={wprojectLoading}
              bodyStyle={{ padding: 0 }}
            >
              {this.getSingproCardInfo(bugProjectTotal,qualitysum).map(item => (
                <Card.Grid className={styles.projectGrid} key={item.id}>
                  <Card bodyStyle={{ padding: 0 }} bordered={false}>
                    <Card.Meta
                      title={
                        <div className={styles.cardTitle}>
                          <Avatar size="small" src={item.logo} />
                          <Link to={item.href}>{item.title}</Link>
                        </div>
                      }
                      description={item.description}
                    />
                    <div className={styles.projectItemContent}>
                      {/* <Link to={item.memberLink}>{item.member || ''}</Link> */}
                      <a >{item.member || ''}</a>
                      {item.updatedAt && (
                        <span className={styles.datetime} title={item.updatedAt}>
                          {moment(item.updatedAt).fromNow()}
                        </span>
                      )}
                    </div>
                    <Divider className={styles.projectDivider} orientation="left">项目质量</Divider>
                    <Row gutter={16}>
                      <Col span={8} className={styles.projectCol}>
                        <Statistic className={styles.projectStatistic} title="质量系数" value={item.quality} />
                      </Col>
                      <Col span={8} className={styles.projectCol}>
                        <Statistic className={styles.projectStatistic} title="质量排名" value={item.rank + '/' + item.count} />
                      </Col>
                      <Col span={8}>
                        <Statistic className={styles.projectStatistic} title="&nbsp;Bug总数" value={item.bugTotal}/>
                      </Col>
                    </Row>
                  </Card>
                </Card.Grid>
              ))}
            </Card>
            <Card
              bodyStyle={{ padding: 0 }}
              bordered={false}
              className={styles.activeCard}
              title="操作动态"
              loading={wactivitiesLoading}
            >
              <List  className={styles.activitiesList} loading={wactivitiesLoading}
                     size="middle"
                     dataSource={this.props.workactivities.data}
                     renderItem={ (item,index)=>{


                       return (
                         <List.Item key={index} > {/*pagination*/}
                           <List.Item.Meta
                             avatar={<Avatar style={{ backgroundColor: '#87d068' }} icon="user"  />}//src={item.user.avatar}
                             title={
                               <span>
                          <span className={styles.event}>{item.real_name}</span>
                             {/*console.log('####',item)*/}
                          <span > {item.project_name ? item.project_name+'项目,' :null}</span>
                          <span >{this.getDynameicAction(item.acition)}</span>
                          <span>{item.option_object}</span>
                        </span>
                             }
                             description={
                               <span className={styles.datetime} >
                          {moment(item.CreationTime).fromNow()}
                        </span>
                             }
                           />
                         </List.Item>
                       )

                     }}
                     pagination={{
                       defaultCurrent:1,
                       size:'small',
                       pageSize: 3,
                       onChange:this.getPages
                     } } >
              </List>
            </Card>
          </Col>
          <Col xl={8} lg={24} md={24} sm={24} xs={24}>
            <Card
              style={{ marginBottom: 24 }}
              title="便捷导航"
              bordered={false}
              bodyStyle={{ padding: 0 }}
            >
              <EditableLinkGroup onAdd={() => {}} links={links} linkElement={Link} />

            </Card>
            {/* <Card bodyStyle={{ paddingTop: 12, paddingBottom: 12 }} bordered={false} title="团队">
              <div className={styles.members}>
                <Row gutter={48}>
                  {members.map(item => (
                    <Col span={12} key={`members-item-${item.id}`}>
                      <Link to={item.link}>
                        <Avatar src={item.logo} size="small" />
                        <span className={styles.member}>{item.title}</span>
                      </Link>
                    </Col>
                  ))}
                </Row>
              </div>
            </Card> */}
          </Col>
        </Row>
      </PageHeaderLayout>
    );
  }
}
